package com.jee.ssm.common.utils.mq.jms;

import javax.jms.DeliveryMode;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.naming.Context;
import javax.naming.InitialContext;

public class SimplePublisher {
	
	private TopicPublisher producer;  
    private TopicSession session;  
    private TopicConnection connection;  
    private boolean isOpen = true;  
      
    public SimplePublisher() throws Exception{  
        Context context = new InitialContext();  
        TopicConnectionFactory connectionFactory = (TopicConnectionFactory)context.lookup("TopicCF");  
        connection = connectionFactory.createTopicConnection();  
        connection.setClientID("OK111");  
        session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);  
        Topic topic = (Topic)context.lookup("topic1");  
        producer = session.createPublisher(topic);//non durable  
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);  
        connection.start();  
          
    }  
      
      
    public boolean send(String text) {  
        if(!isOpen){  
            throw new RuntimeException("session has been closed!");  
        }  
        try{  
            Message message = session.createTextMessage(text);  
            producer.send(message);  
            return true;  
        }catch(Exception e){  
            return false;  
        }  
    }  
      
    public synchronized void close(){  
        try{  
            if(isOpen){  
                isOpen = false;  
            }  
            session.close();  
            connection.close();  
        }catch (Exception e) {  
            //  
        }  
    }  

}
